package model.analyzer;

import japa.parser.JavaParser;
import japa.parser.ParseException;
import japa.parser.ast.CompilationUnit;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.StringBufferInputStream;
import java.util.HashSet;

import de.linguatools.disco.DISCO;

import model.analyzer.idSplitter.IDSplitter;
import model.core.code.ClassData;

import DAO.ICodeDAO;
import DAO.mysql.MySQLDAO;

public class ISExtractorMain {
	private static MySQLDAO sqlDAO = new MySQLDAO();
//	private static HashSet<String> parsed;
	private static RandomAccessFile persistData;// = new RandomAccessFile("./record/analyzed", "rw");
	private static IDSplitter splitter;
	
	public static void parse(int srcID) throws ParseException, IOException {
		ClassData clsDt = sqlDAO.getCodeDAO().getClassData(srcID);
		if(clsDt.getSourceCode() != null) {
			try {
				StringBufferInputStream is = new StringBufferInputStream(clsDt.getSourceCode());
				CompilationUnit root = JavaParser.parse(is);
				ExtractorVisitor visitor = new ExtractorVisitor(sqlDAO, splitter);
				root.accept(visitor, null);
				is.close();
			} catch (Throwable t) {
				t.printStackTrace();
			}
		}
		persistData.seek(0);
		persistData.writeInt(srcID);
	}
	
//	public static void saveParsed() {
//		File f = new File("./record/parsed.dat");
//		if(!f.exists()) {
//			try {
//				f.createNewFile();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//		try {
//			ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f));
//			os.writeObject(parsed);
//			os.close();
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

	public static void main(String[] args) throws ParseException, FileNotFoundException, IOException, ClassNotFoundException {
		File f = new File("./record/parsed.dat");
		if(!f.exists()) {
			f.createNewFile();
		}
		persistData = new RandomAccessFile("./record/idanalyzed", "rw");
		splitter = new IDSplitter(new DISCO("en_wiki", false));
		persistData.seek(0);
		int currentSrc = 1;
		try {
			currentSrc = persistData.readInt();
		} catch (Throwable t) {
			//do nothing...
		}
		while(true) {
			parse(currentSrc);
			System.out.println(currentSrc + " parsed..");
			++currentSrc;
		}
	}
}
